package com.selfdriving.activity;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.selfdriving.R;
import com.selfdriving.utils.Base64;

public class RegisterTwoActivity extends BaseActivity
{

	@ViewInject(id = R.id.top_text_name)
	TextView top_text_name;

	@ViewInject(id = R.id.top_text_step)
	TextView top_text_step;

	@ViewInject(id = R.id.tvVerify)
	TextView tvVerify;

	@ViewInject(id = R.id.btn_send, click = "btn_send")
	Button btn_send;

	@ViewInject(id = R.id.btn_back, click = "btn_back")
	Button btn_back;

	@ViewInject(id = R.id.btn_ok, click = "btn_ok")
	Button btn_ok;

	private TimeCount time;
	public static EditText numbers;
	private String strForm = "验证码已经发送到 <font color='#f4a600'><U >%s</U></font>";
	int authCode = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_two);
		numbers = (EditText) findViewById(R.id.et_number);
		time = new TimeCount(60000, 1000);
		top_text_name.setText("输入手机验证码");
		top_text_step.setText("2/3");
	}

	public void btn_send(View v)
	{
		Intent intent = super.getIntent();
		String phone = intent.getStringExtra("phone");
		String txtstr = String.format(strForm, "(+86)" + phone);
		Spanned spt = Html.fromHtml(txtstr);
		tvVerify.setText(spt);
		tvVerify.setVisibility(View.VISIBLE);
		time.start();
		createCode();
		sendAuthCode(phone);
	}

	private void createCode()
	{
		showToast("验证码获取中,请稍后留意短信。");
		authCode = (int) ((Math.random() * 9 + 1) * 10000);// 产生一个5位数的随机数
		System.out.println(authCode + "---");
	}

	public void btn_back(View v)
	{
		this.finish();
	}

	public void btn_ok(View v)
	{
		Intent intent = new Intent(this, RegisterThreeActivity.class);
		startActivity(intent);
	}

	class TimeCount extends CountDownTimer
	{
		public TimeCount(long millisInFuture, long countDownInterval)
		{
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish()
		{// 计时完毕时触发
			btn_send.setText("重发");
			btn_send.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished)
		{// 计时过程显示
			btn_send.setClickable(false);
			btn_send.setText(millisUntilFinished / 1000 + "秒");
		}
	}

	public void sendAuthCode(String phone)
	{
		try
		{
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mobilephone", phone); // 返回包
			jsonObject.put("message", "验证码：" + authCode
					+ "，您正在使用智慧旅游注册功能，如非本人操作，请立即删除！");
			HttpEntity entity = new StringEntity(jsonObject.toString(), "UTF-8");
			Header[] headers = new Header[2];
			String key = Base64.encode(String.format("Android%s",
					dateFormat(new Date(), "yyyyMMDD")).getBytes());
			String ipkey = Base64.encode(getLocalIpAddress().getBytes());
			headers[0] = new BasicHeader("requestHeaderKey", key);
			headers[1] = new BasicHeader("remoteKey", ipkey);

			FinalHttp fh = new FinalHttp();
			fh.post("http://120.203.228.225:8890/ticket/access.ews?cmd=sendMessage",
					headers, entity, "UTF-8", new AjaxCallBack<Object>()
					{
						@Override
						public void onFailure(Throwable t, String strMsg)
						{
							showToast("获取验证码失败,请检查网络。");
						}

						@Override
						public void onSuccess(Object o)
						{
							try
							{
								System.out.println("请求成功！");
							} catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					});
		} catch (Exception e)
		{
			// TODO: handle exception
		}

	}

	public String getLocalIpAddress()
	{
		try
		{
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();)
			{
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();)
				{
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress())
					{
						return inetAddress.getHostAddress();
					}
				}
			}
		} catch (SocketException ex)
		{
			Log.e(this.getClass().getSimpleName(), ex.toString());
		}
		return null;
	}

	public static String dateFormat(Date date, String type)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(type);
		return sdf.format(date);
	}
}
